<?php

/**
 * wtfphp框架
 * 版本：1.1.0
 * 意见/BUG：wtfphp@sina.com
 */
class wtfphp {
    /*-------- 变量 --------*/
    private static $app_path;   //项目目录
    private static $module;     //当前模块
    private static $controller; //当前控制器
    private static $action;     //当前操作

    /**
     * 框架入口
     */
    static function app($app_path) {
        if (!is_dir($app_path)) {
            throw new \Exception("[$app_path] is not a directory!");
        }
        self::$app_path = $app_path;

        $url = \wtfphp\router::run();
        self::$module = $url['module'];
        self::$controller = $url['controller'];
        self::$action = $url['action'];

        self::autoLoad($app_path, $url['module']);
        self::load($url['module'], $url['controller'], $url['action']);
    }

    /**
     * 替换特殊字符
     */
    static function replace($string) {
        return str_replace(
            array(
                '{:app_path}',
                '{:module}',
                '{:controller}',
                '{:action}',
            ),
            array(
                self::$app_path,
                self::$module,
                self::$controller,
                self::$action,
            ),
            $string);
    }

    /**
     * 注册目录
     */
    private static function autoLoad($app_path, $module) {
        //控制器
        \wtfphp\loader::registerNamespace(
            "$module\controllers",  //命名空间
            $app_path . '/modules/' . $module . '/controllers/' //目录
        );
        //模型
        \wtfphp\loader::registerNamespace(
            'models',   //命名空间
            $app_path . '/models/'  //目录
        );
    }

    /**
     * 运行
     * @param $m    模块
     * @param $c    控制器
     * @param $a    操作
     */
    private static function load($m, $c, $a) {
        $name = "\\$m\controllers\\{$c}Controller";
        if (!class_exists($name)) {
            throw new \Exception("[$name] not found!");
        }
        $obj = new $name();
        $name = $a . 'Action';
        if (!method_exists($obj, $name)) {
            throw new \Exception("[$name] not found!");
        }
        $obj->$name();
    }
}

/*-------------------- 启动 --------------------*/
//框架根目录
define('WTFPHP_PATH', __DIR__ . '/');
//载入核心文件
require WTFPHP_PATH . 'drive/di.php';
require WTFPHP_PATH . 'drive/loader.php';
require WTFPHP_PATH . 'drive/router.php';
require WTFPHP_PATH . 'drive/base.php';
require WTFPHP_PATH . 'drive/controller.php';
require WTFPHP_PATH . 'drive/model.php';
//注册框架类库
\wtfphp\loader::registerNamespace('wtfphp\libs', WTFPHP_PATH . 'libs/');